package com.changcheng.explorer.event;

import java.io.File;
import java.util.HashMap;
import java.util.Set;
import com.changcheng.explorer.R;
import com.changcheng.explorer.service.FileListService;
import android.graphics.Color;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * GridView被单击事件
 * 
 * @author Administrator
 * 
 */
public class GVOnItemClickListener implements OnItemClickListener {

	@SuppressWarnings("unused")
	private static final String TAG = "LVOnItemClickListener";
	private FileListService fileListService;

	public GVOnItemClickListener(FileListService fileListService) {
		this.fileListService = fileListService;
		fileListService.home();
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// 是否为选择状态
		if (this.fileListService.isCanSelect()) {
			// 设置选中或取消选中文件
			Set<Integer> selected = this.fileListService.getSelected();
			for (Integer item : selected) {
				if (item.equals(position)) {
					// 取消选中
					view.setBackgroundColor(Color.TRANSPARENT);
					selected.remove(position);
					return;
				}
			}
			// 选中并添加到选中文件列表
			view.setBackgroundResource(R.drawable.selectedColor);
			selected.add(position);

		} else {
			// 获取被单击的列表项
			HashMap<String, Object> item = (HashMap<String, Object>) this.fileListService
					.getGridView().getItemAtPosition(position);
			String current = this.fileListService.getCurrentPosition();
			File file = new File(current + "/" + (String) item.get("file"));
			
			// 显示子文件列表
			if (file.isDirectory()) {
				this.fileListService.fill(file.getPath());
				this.fileListService.change(file.getPath());
			} else {
			// 打开文件	
				this.fileListService.open(file.getPath());
			}
		}
	}
}
